package com.mainbo.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.common.constant.Const;
import com.mainbo.modular.system.model.PtRole;
import com.mainbo.modular.system.dao.PtRoleMapper;
import com.mainbo.modular.system.model.Role;
import com.mainbo.modular.system.service.IPtRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author moshang
 * @since 2020-02-26
 */
@Service
public class PtRoleServiceImpl extends ServiceImpl<PtRoleMapper, PtRole> implements IPtRoleService {
    @Resource
    private PtRoleMapper ptRoleMapper;

    @Override
    public List<PtRole> getRoleByScope(String orgId, Integer scope) {
        EntityWrapper<PtRole> role = this.getRole(scope, orgId);
        return ptRoleMapper.selectList(role);
    }

    @Override
    public List<PtRole> getDelRoleByOrgId(String orgId) {
       EntityWrapper<PtRole> delRole = new EntityWrapper<>();
        delRole.eq("org_id",orgId);
        delRole.eq("is_del",1);
        return ptRoleMapper.selectList(delRole);
    }

    private EntityWrapper<PtRole> getRole(Integer scope, String orgId) {
        // 获取已经删除的系统职务
       EntityWrapper<PtRole>  role = new EntityWrapper<>();
        role.eq("scope",scope);
        List<String> orgIds = new ArrayList<>();
        orgIds.add(Const.DEFAULT_ORG_ID);
        if (orgId != null) {
            orgIds.add(orgId);
        }
        List<Integer> delRoleId = this.getDelRoleIds(orgId);
        role.eq("is_del",0);
        role.in("org_id",orgIds);
        role.notIn("id",delRoleId);
        role.orderAsc(Collections.singleton("sort"));
        return role;
    }


    private List<Integer> getDelRoleIds(String orgId) {
        List<Integer> delRoleId = new ArrayList<Integer>();
        delRoleId.add(-1);
        // 获取已经删除的系统职务
        if (!Const.DEFAULT_ORG_ID.equals(orgId)) {
            List<PtRole> findAllDel = this.getDelRoleByOrgId(orgId);
            for (PtRole del : findAllDel) {
                delRoleId.add(del.getRelId());
            }
        }
        return delRoleId;
    }
}
